//  用药方案列表
//  TherapeuticRegimenViewController.m
//  yilutongxing
//
//  Created by ios-21 on 17/4/15.
//  Copyright © 2017年 YZE. All rights reserved.
//
#import "UIImage+ColorImage.h"
#import "UITableView+EmptyData.h"
#import <QMUITips.h>
#import <QMUIDialogViewController.h>
#import <QMUINavigationController.h>
#import "iCarousel.h"
#import "CommonDefine.h"
#import "TherapeuticRegimenViewController.h"
#import "TheraRementTableViewCell.h"
#import "TabletPlanViewController.h"
#import "RPMedicinePlan.h"
#import "RPMedicineSinglePlan.h"
#import "TherapeuticCardController.h"

#define URL_GetMedicinePlan @"/api/sick-medicine-plans/mine?sort=startTime,asc"
#define URL_DeletePlan @"/api/sick-medicine-plans/"

#define ROWH_TIMERANGE 33 //时间范围行高
#define ROWH_MEDICINENAME 44  //药品名称行高
#define ROWH_FREQROW 36  //服药频率行高
#define H_BUTTON 27 //操作按钮高度
#define W_BUTTON 40 //按钮宽度

#define BODY_BASE_Y ([[UIApplication sharedApplication] statusBarFrame].size.height + self.navigationController.navigationBar.frame.size.height)
#define PAGE_OFFSET 30

#define CELL_ID @"c"

@interface TherapeuticRegimenViewController ()<iCarouselDelegate, iCarouselDataSource, TabletPlanViewBackDelegate,
                                                TherapeuticCardControllerEventDelegate>
@property(nonatomic, strong) iCarousel *carousel;
@property(nonatomic, strong) UIImageView *navi_under_line;
@property(nonatomic, strong) NSMutableArray *plans;
@property(nonatomic, strong) NSMutableArray *card_controller_arr;
@property(nonatomic, assign) uint32_t pageNum;
@end

static NSInteger item_height = 0;
@implementation TherapeuticRegimenViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title=@"用药方案";
    [self initUI];
    
    //请求数据
    [[YZENetwork sharedInstace] getRequestWithUrl:[NSString stringWithFormat:@"%@%@&page=%d&size=%d", BASE, URL_GetMedicinePlan, self.pageNum, PAGESIZE]
                                       parameters:nil
                                         delegate:self
                                       requestTag:1
                                     successBlock:^(id responseObject)
    {
        self.plans = [RPMedicinePlan mj_objectArrayWithKeyValuesArrayAdd:responseObject];
        [self initCardControllerArr];
        [self.carousel reloadData];
        [self.carousel scrollToItemAtIndex:self.plans.count-1 animated:NO];
    }];
}

- (void)initUI{
    NSInteger sH = SCREEN_HEIGHT;
    NSInteger baseY = BODY_BASE_Y;
    item_height = sH - baseY - 15 - 60;
    
    _carousel = [[iCarousel alloc] initWithFrame:CGRectMake(0, baseY + 15, SCREEN_WIDTH, item_height)];
    _carousel.delegate = self;
    _carousel.dataSource = self;
    _carousel.bounces = NO;
    _carousel.pagingEnabled = YES;
    _carousel.type = iCarouselTypeCustom;
    [self.view addSubview:_carousel];
    //[self.collectionView registerNib:[UINib nibWithNibName:@"TheraRementTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"detailCell"];
    
    UIImage *leftImage=[[UIImage imageNamed:@"返回"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem *leftButtonItem=[[UIBarButtonItem alloc]initWithImage:leftImage style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem=leftButtonItem;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"添加" style:UIBarButtonItemStyleDone target:self action:@selector(newPlan)];
    //设置navigantionBar背景色
    UIView *navibg = [[UIView alloc]initWithFrame:self.navigationController.navigationBar.bounds];
    navibg.backgroundColor = WHITE_COLOR;
    [self.navigationController.navigationBar setValue:navibg forKey:@"backgroundView"];
    self.navi_under_line = [UIImage findHairlineImageViewUnder:self.navigationController.navigationBar];
    self.navi_under_line.hidden = YES;
    self.view.backgroundColor = COLOR(248, 248, 248);
    
    UIButton *btn_copy = [[UIButton alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 36, SCREEN_WIDTH, 30)];
    btn_copy.tag = 666;
    [btn_copy setTintColor:COLOR(20, 20, 255)];
    [btn_copy setTitleColor:COLOR(20, 20, 255) forState:UIControlStateNormal];
    [btn_copy setTitle:@"以此为蓝本新增方案" forState:UIControlStateNormal];
    [btn_copy addTarget:self action:@selector(copyPlan:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn_copy];
}

-(void)viewWillAppear:(BOOL)animated{
    if (_navi_under_line) {
        _navi_under_line.hidden = YES;
    }
}
- (void)viewWillDisappear:(BOOL)animated{
    if (_navi_under_line) {
        _navi_under_line.hidden = NO;
    }
}

-(void)back{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - iCarousel 代理
-(UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSInteger)index reusingView:(UIView *)view{
    TherapeuticCardController *card_controller = self.card_controller_arr[index];
    [card_controller setPlanData:self.plans[index] forLatest:self.plans.count-1==index];
    view = card_controller.tableView;
    return view;
}

-(CATransform3D)carousel:(iCarousel *)carousel itemTransformForOffset:(CGFloat)offset baseTransform:(CATransform3D)transform{
    static CGFloat max_scale = 1.0f;
    static CGFloat min_scale = 0.8f;
    if (offset <= 1 && offset >= -1) {
        float tempScale = offset < 0 ? 1+offset : 1-offset;
        float slope = (max_scale - min_scale) / 1;
        
        CGFloat scale = min_scale + slope*tempScale;
        transform = CATransform3DScale(transform, scale, scale, 1);
    }else{
        transform = CATransform3DScale(transform, min_scale, min_scale, 1);
    }
    
    return CATransform3DTranslate(transform, offset * self.carousel.itemWidth * 1.2, 0.0, 0.0);
}

-(NSInteger)numberOfItemsInCarousel:(iCarousel *)carousel{
    return self.plans.count;
}

#pragma mark 业务逻辑
//新增方案
-(void)newPlan{
    TabletPlanViewController *vc = [TabletPlanViewController new];
    vc.delegate = self;
    vc.index = 0;
    vc.isOnlyLocal = NO;
    vc.isAdd = YES;
    UINavigationController *navi=[[UINavigationController alloc]initWithRootViewController:vc];
    [self presentViewController:navi animated:YES completion:nil];
}
//以蓝本新增方案
-(void)copyPlan:(UIButton*)sender{
    TabletPlanViewController *vc = [TabletPlanViewController new];
    vc.plan = _plans[self.carousel.currentItemIndex];
    vc.delegate = self;
    vc.index = 0;
    vc.isAdd = YES;
    UINavigationController *navi=[[UINavigationController alloc]initWithRootViewController:vc];
    [self presentViewController:navi animated:YES completion:nil];
}
//修改已有方案
-(void)modifyPlan{
    TabletPlanViewController *vc = [TabletPlanViewController new];
    vc.delegate = self;
    vc.__title = @"修改方案";
    vc.index = self.carousel.currentItemIndex;
    vc.plan = self.plans[self.carousel.currentItemIndex];
    UINavigationController *v=[[UINavigationController alloc]initWithRootViewController:vc];
    [self presentViewController:v animated:YES completion:nil];
}
-(void)deletePlan{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请确认" message:@"确定要删除这个用药方案吗？" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action_cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [alert dismissViewControllerAnimated:YES completion:nil];
    }];
    UIAlertAction *action_confirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [alert dismissViewControllerAnimated:YES completion:nil];
        [self postDeletePlanReq:self.carousel.currentItemIndex];
    }];
    [alert addAction:action_cancel];
    [alert addAction:action_confirm];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - 用药方案卡片UI代理
-(void)postDeletePlanReq:(long)index{
    RPMedicinePlan *plan = _plans[index];
    [[YZENetwork sharedInstace] deleteRequestWithUrl:[NSString stringWithFormat:@"%@%@%ld", BASE, URL_DeletePlan, plan.id] parameters:nil delegate:self requestTag:1 successBlock:^(id responseObject) {
        [QMUITips showInfo:@"已删除" inView:self.view hideAfterDelay:2];
        [_plans removeObjectAtIndex:index];
        [self initCardControllerArr];
        [self.carousel reloadData];
        [self.carousel scrollToItemAtIndex:self.plans.count-1 animated:NO];
    }];
}

#pragma mark - TabletPlanViewBackDelegate
- (void)updatePlanFor:(RPMedicinePlan *)plan index:(long)index{
    _plans[index] = plan;
    TherapeuticCardController *card_controller = self.card_controller_arr[index];
    [card_controller setPlanData:plan forLatest:self.plans.count-1==index];
}
- (void)addPlanFor:(RPMedicinePlan *)plan{
    [_plans addObject:plan];
    [self initCardControllerArr];
    [self.carousel reloadData];
    [self.carousel scrollToItemAtIndex:self.plans.count-1 animated:NO];
}

#pragma mark - TherapeuticCardControllerEventDelegate
- (void)OnDeleteBtnClick{
    debugLog(@"[SHENMI][OnDeleteBtnClick]");
    [self deletePlan];
}
- (void)OnModifyBtnClick{
    debugLog(@"[SHENMI][OnModifyBtnClick]");
    [self modifyPlan];
}

#pragma mark - 数据配置
- (NSMutableArray *)card_controller_arr{
    if (!_card_controller_arr) {
        _card_controller_arr = [NSMutableArray array];
    }
    return _card_controller_arr;
}

#pragma mark - 辅助函数
- (void)initCardControllerArr{
    CGFloat viewWidth = SCREEN_WIDTH - 2*PAGE_OFFSET;
    CGRect card_frame = CGRectMake(0, 0, viewWidth, item_height);
    unsigned long begin = self.card_controller_arr.count;
    unsigned long end = self.plans.count;
    for (;begin<end; begin++) {
        TherapeuticCardController *card_controller = [[TherapeuticCardController alloc]initWithViewFrame:card_frame];
        card_controller.delegate = self;
        [self.card_controller_arr addObject:card_controller];
    }
}

@end
